<?php  
class ConfigModel extends Model{

	public $table='config';

	/**
	 * 获取配置项
	 * @return [type] [description]
	 */
	public function get(){
		//配置项分组依据 1主要2水印3上传4其他
		$cgid=Q('cgid',0,'intval');
		$cgid?$map=array("isshow"=>array('EQ',1),"cgid"=>array('EQ',$cgid)):$map['isshow']=array("EQ",1);
		//获取所有要显示的配置项 并排序
		$config=$this->where($map)->order("orderlist")->all();

		foreach ($config as $k=> $c) {

			$type='_'.$c['type'];

			$config[$k]['html']=$this->$type($c);
		}
		return $config;
	}
	/**
	 * 文本输入
	 * @param [array] $config [配置项]
	 * @return [type] [description]
	 */
	public function _text($config){

		return "<input type='text' name='{$config['name']}' value='{$config['value']}' class='w200'/>";
	}
	/**
	 * 单选框
	 * @param  [type] $config [description]
	 * @return [type]         [description]
	 */
	public function _radio($config){

		$data=explode(',', $config['info']);
		
		$html='';

		foreach ($data as $id => $d) {

			$info=explode('|', $d);

			//选中属性
			$checked=$info[0]==$config['value'] ? " checked='' " :'';

			$html.="<lable><input type='radio' name='{$config['name']}' value='{$info[0]}' $checked class='w40'/>{$info[1]}</lable>";
		}
		
		return $html;
	}
	/**
	 * 文本域
	 * @param  [type] $config [description]
	 * @return [type]         [description]
	 */
	public function _textarea($config){

		return "<textarea name='{$config['name']}' class='w200 h100'>{$config['value']}</textarea>";
	}
	/**
	 * 创建配置文件
	 * @return [type] [description]
	 */
	public function createConfigFile(){
		//获取两个字段 第一个字段作键名   第二个字段做键值
		$config=$this->getField('name,value');
		
		//转成合法php语言
		$data="<?php \nreturn ".var_export($config,true).";\n ?>";
		
		return file_put_contents(APP_CONFIG_PATH.'base.php', $data);
	}
	/**
	 * 设置配置表中的配置项
	 */
	public function setConfig(){
		//去除无效字段
		$_POST=array_filter($_POST);

		foreach ($_POST as $name => $value) {

			$data['value']=$value;

			if (!$this->where("name='$name'")->save($data)) {

				$this->error="操作失败";
			}
		}
		return $this->createConfigFile();
	}
}
?>